import { presetAttributify, presetUno, transformerDirectives } from "unocss";
import presetIcons from "@unocss/preset-icons";
import { compareColors, stringToColor } from "@iconify/utils/lib/colors";
import {
  importDirectory,
  parseColors,
  runSVGO,
  deOptimisePaths
} from "@iconify/tools";

export default {
  safelist: [],
  presets: [
    presetAttributify({
      /* preset options */
      prefix: "w:",
      prefixedOnly: false,
      ignoreAttributes: []
    }),
    presetUno(),
    presetIcons({
      prefix: "i-",
      extraProperties: {
        display: "inline-block",
        "vertical-align": "middle"
      },
      collections: {
        custom: async () => {
          // Load icons
          const iconSet = await importDirectory("src/assets/icons", {
            prefix: "custom"
          });

          // Clean up each icon
          await iconSet.forEach(async name => {
            const svg = iconSet.toSVG(name)!;

            // Change color to `currentColor`
            const blackColor = stringToColor("black")!;

            await parseColors(svg, {
              defaultColor: "currentColor",
              callback: (attr, colorStr, color) => {
                // console.log('Color:', colorStr, color);

                // Change black to 'currentColor'
                if (color && compareColors(color, blackColor)) {
                  return "currentColor";
                }

                switch (color?.type) {
                  case "none":
                  case "current":
                    return color;
                }

                throw new Error(
                  `Unexpected color "${colorStr}" in attribute ${attr}`
                );
              }
            });

            // Optimise
            runSVGO(svg);

            // Update paths for compatibility with old software
            await deOptimisePaths(svg);

            // Update icon in icon set
            iconSet.fromSVG(name, svg);
          });

          // Export as IconifyJSON
          return iconSet.export();
        }
      }
    })
  ],
  shortcuts: {
    "wh-full": "w-full h-full",
    "wh-screen": "w-screen h-screen",
    "flex-ac": "flex justify-around items-center",
    "flex-bc": "flex justify-between items-center",
    "flex-cc": "flex justify-center items-center",
    "flex-sc": "flex justify-start items-center",
    "flex-ec": "flex justify-end items-center",
    "abso-lt": "absolute left-0 top-0",
    "abso-rt": "absolute right-0 top-0",
    "abso-lb": "absolute left-0 bottom-0",
    "abso-rb": "absolute right-0 bottom-0"
  },
  rules: [],
  transformers: [transformerDirectives()]
};
